package com.example.deliveryapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class RestaurantMenuPageActivity extends AppCompatActivity {

    private TextView restaurantNameView;
    private TextView restaurantDescriptionView;
    private TextView restaurantRatingView;
    private ImageView restaurantCoverView;
    private RecyclerView menuRecyclerView;
    private TextView checkoutButton;
    private TextView totalQuantityTextView;
    private TextView totalPriceTextView;
    private List<Menu> menus;
    private MenuAdapter menuAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurant_menu_page);

        // 初始化 UI 组件
        restaurantNameView = findViewById(R.id.restaurant_name);
        restaurantDescriptionView = findViewById(R.id.restaurant_description);
        restaurantCoverView = findViewById(R.id.restaurant_cover);
        restaurantRatingView = findViewById(R.id.restaurant_rating);
        menuRecyclerView = findViewById(R.id.menu_recycler_view);
        checkoutButton = findViewById(R.id.checkout_button);
        totalQuantityTextView = findViewById(R.id.total_quantity);
        totalPriceTextView = findViewById(R.id.total_price);

        // 初始化菜单数据
        menus = getSampleMenus();

        // 从 Intent 获取数据
        Intent intent = getIntent();
        String restaurantName = intent.getStringExtra("restaurant_name");
        float rating = intent.getFloatExtra("restaurant_rating", 0); // 提供默认值
        int coverImageResourceId = intent.getIntExtra("restaurant_cover_image", 0); // 提供默认图片资源 ID

        // 设置店铺名称和评分
        restaurantNameView.setText(restaurantName);
        restaurantRatingView.setText(String.valueOf(rating));
        restaurantDescriptionView.setText("Welcome to " + restaurantName);

        // 设置封面图片
        restaurantCoverView.setImageResource(coverImageResourceId);

        // 初始化 RecyclerView
        menuAdapter = new MenuAdapter(menus, this::onQuantityChanged);
        menuRecyclerView.setAdapter(menuAdapter);
        menuRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 初始化结账按钮
        checkoutButton.setOnClickListener(v -> {
            // 当点击结账按钮时，显示订单摘要对话框
            showOrderSummary();
        });

        updateTotals();

        ImageButton back_on_menu = findViewById(R.id.back_on_menu);
        back_on_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 结束当前Activity，返回上一Activity
            }
        });

        // 设置 totalQuantityTextView 的点击事件
        totalQuantityTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOrderSummary();
            }
        });
    }

    private void updateTotals() {
        double total = 0;
        int totalQuantity = 0;
        for (Menu menu : menus) {
            total += menu.getPrice() * menu.getSelectedQuantity();
            totalQuantity += menu.getSelectedQuantity();
        }
        totalQuantityTextView.setText("Nums:" + String.valueOf(totalQuantity));
        totalPriceTextView.setText(String.format("$%.2f", total));
    }

    private double getTotalPrice() {
        double total = 0;
        for (Menu menu : menus) {
            total += menu.getPrice() * menu.getSelectedQuantity();
        }
        return total;
    }

    // 显示订单摘要的对话框
    private void showOrderSummary() {
        // 计算总金额和订单详情
        double total = getTotalPrice();
        StringBuilder orderDetails = new StringBuilder();
        for (Menu menu : menus) {
            int quantity = menu.getSelectedQuantity();
            if (quantity > 0) {
                orderDetails.append(menu.getName())
                        .append(": ")
                        .append(quantity)
                        .append(" 份")
                        .append(", 单价: $")
                        .append(String.format("%.2f", menu.getPrice()))
                        .append("\n");
            }
        }
        String orderSummary = "已选菜品：\n" + orderDetails.toString();

        // 创建 AlertDialog 构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(RestaurantMenuPageActivity.this);
        builder.setTitle("订单摘要")
                .setMessage(orderSummary + "\n总计: $" + String.format("%.2f", total))
                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss()) // 用户可以继续点菜
                .setNegativeButton("结算", (dialog, which) -> {
                    // 启动 CheckOutPageActivity 并传递总金额和已选择的菜品
                    Intent checkoutIntent = new Intent(RestaurantMenuPageActivity.this, CheckOutPageActivity.class);
                    checkoutIntent.putExtra("total_price", total); // 传递正确的总金额
                    checkoutIntent.putParcelableArrayListExtra("order_items", new ArrayList<>(menus)); // 传递所有菜品数据
                    startActivity(checkoutIntent);
                });

        // 显示对话框
        builder.create().show();
    }

    private List<Menu> getSampleMenus() {
        List<Menu> menus = new ArrayList<>();
        menus.add(new Menu("Pizza", "Delicious cheese pizza", 9.99, R.drawable.pizza));
        menus.add(new Menu("Burger", "Juicy beef burger", 5.99, R.drawable.burger));
        menus.add(new Menu("Soda", "Coca-cola 300ml", 1.99, R.drawable.soda));
        return menus;
    }

    public void onQuantityChanged(Menu menu) {
        menuAdapter.notifyItemChanged(menuAdapter.getMenuList().indexOf(menu));
        updateTotals();
    }
}